package com.kfm.hotel.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.PageInfo;
import com.kfm.hotel.domain.SysUser;
import com.kfm.hotel.service.SysUserService;
import com.kfm.hotel.util.MD5Util;
import com.kfm.hotel.util.R;
import org.apache.coyote.Response;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/sysuser")

public class SysUserController {
  @Autowired
  private SysUserService service;


      @GetMapping
      public ModelAndView index() {
          ModelAndView modelAndView01 = new ModelAndView("sysuser/index");
          return modelAndView01;
      }

      //查询所有的数据
    //limit:最大页数
      @GetMapping("/list")
      public R list(@RequestParam(defaultValue = "1") Integer page,
                    @RequestParam(defaultValue = "10") Integer limit,
                    SysUser user){
          //后端实现分页
          PageInfo<SysUser> list = service.list(user, page, limit);
          return R.ok(list);
      }
    /**
     * 到处excel文件
     */
    @GetMapping("/export")
    public ResponseEntity<InputStreamResource> export(Integer type, HttpServletResponse response) throws IOException {
        List<SysUser> list=null;
        String fileName="demo.xlsx";
        if(type==null){
            //查询所有数据
            list = service.list();
            fileName="user.xlsx";
        }else {
            //创建一个空列表
            list= Collections.emptyList();
        }
        // 通过 poi 将数据写入到 excel 表格中
        XSSFWorkbook sheets = new XSSFWorkbook();
        XSSFSheet sheet = sheets.createSheet("用户信息表");
        //设置表头
        Row row0 = sheet.createRow(0);
        Cell cell0 = row0.createCell(0);
        cell0.setCellValue("id");
        Cell cell1 = row0.createCell(1);
        cell1.setCellValue("用户名");
        Cell cell2 = row0.createCell(2);
        cell2.setCellValue("邮箱");
        Cell cell3 = row0.createCell(3);
        cell3.setCellValue("密码");
        Cell cell4 = row0.createCell(4);
        cell4.setCellValue("真实姓名");
        Cell cell5 = row0.createCell(5);
        cell5.setCellValue("手机号");
        if (type == null) {
            // 导出全部
            Cell cell6 = row0.createCell(6);
            cell6.setCellValue("创建时间");
            CellStyle cellStyle = sheets.createCellStyle();
            // 设置宽度
            sheet.setColumnWidth(6, 20 * 256);
            // 文字居中
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cell6.setCellStyle(cellStyle);
            Cell cell7 = row0.createCell(7);
            cell7.setCellValue("修改时间");
            Cell cell8 = row0.createCell(8);
            cell8.setCellValue("是否删除");
            Cell cell9 = row0.createCell(9);
            cell9.setCellValue("状态");
        }

        int rowCount = 1;
        for (SysUser item : list) {
            Row row = sheet.createRow(rowCount++);
            Cell cell = row.createCell(0); // 假设导出到第一列
            cell.setCellValue(item.getId());
            Cell cell10 = row.createCell(1);
            cell10.setCellValue(item.getUsername());
            Cell cell11 = row.createCell(2);
            cell11.setCellValue(item.getEmail());
            Cell cell12 = row.createCell(3);
            cell12.setCellValue(item.getPassword());
            Cell cell13 = row.createCell(4);
            cell13.setCellValue(item.getName());
            Cell cell14 = row.createCell(5);
            cell14.setCellValue(item.getPhone());
            Cell cell15 = row.createCell(6);
            cell15.setCellValue(item.getCreateTime().toLocaleString());
            Cell cell16 = row.createCell(7);
            //如果更新时间为空，怎么用“”代替，如果有时间则用当地时间代替
            cell16.setCellValue(ObjectUtils.isEmpty(item.getUpdateTime()) ? "" : item.getUpdateTime().toLocaleString());
            Cell cell17 = row.createCell(8);
            cell17.setCellValue(item.getIsDel());
            Cell cell18 = row.createCell(9);
            cell18.setCellValue(item.getState());
        }
        //创建字节输出流
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        //用字节流写入excel;
        sheets.write(stream);
        InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(stream.toByteArray()));
        HttpHeaders headers=new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename="+fileName);
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .body(resource);


    }

    /**
     * 导入excel文件
     * @param file
     * @return
     */
      @PostMapping("/import")
      public R importData(MultipartFile file){
          try {
              //使用输入流上传文件
              InputStream inputStream = file.getInputStream();
              XSSFWorkbook sheets = new XSSFWorkbook(inputStream);
              XSSFSheet sheet = sheets.getSheetAt(0);

              List<SysUser> list = new ArrayList<>();
              //迭代每一个单元格的值，每一行
              Iterator<Row> iterator = sheet.iterator();
              if(iterator.hasNext()){
                  //跳过第一行
                  iterator.next();
              }
              while (iterator.hasNext()){
               Row row=iterator.next();
                  SysUser sysUser = new SysUser();
                  //导入第一列数据
                  Cell cell = row.getCell(1);
                  if(cell==null){
                      continue;
                  }
                  cell.setCellType(CellType.STRING);
                  sysUser.setUsername(cell.getStringCellValue());
                  Cell cell1 = row.getCell(2); // 假设导入的是第二列数据
                  cell1.setCellType(CellType.STRING);
                  sysUser.setEmail(cell1.getStringCellValue());
                  Cell cell2 = row.getCell(3); // 假设导入的是第三列数据
                  cell2.setCellType(CellType.STRING);
                  //密码加密
                  sysUser.setPassword(MD5Util.MD5(cell2.getStringCellValue(), sysUser.getUsername()));
                  Cell cell3 = row.getCell(4); // 假设导入的是第四列数据
                  cell3.setCellType(CellType.STRING);
                  sysUser.setName(cell3.getStringCellValue());
                  Cell cell4 = row.getCell(5); // 假设导入的是第五列数据
                  cell4.setCellType(CellType.STRING);
                  sysUser.setPhone(cell4.getStringCellValue());
                  //判断用户是否存在
                  try {
                      service.existUsername(sysUser);
                  }catch (Exception e){
                      e.printStackTrace();
                      continue;
                  }
                  list.add(sysUser);
              }
              //批量插入数据
              boolean b = service.saveBatch(list);
              return b ? R.ok("导入成功"):R.fail("导入失败，请检查格式");
          } catch (IOException e) {
              throw new RuntimeException(e);
          }

      }


      @GetMapping("/add")
     public ModelAndView add(){
      ModelAndView modelAndView02 = new ModelAndView("sysuser/add");
      return modelAndView02;
    }

    @PostMapping("/add")
    public R add(@RequestBody SysUser user){
        int user1 = service.saveSysUser(user);
        //判断添加是否成功
        if(user1>0){
            return R.ok("添加成功！");
        }else{
            return R.fail("添加失败");
        }
    }

    @GetMapping("/edit{id}")
    public ModelAndView edit(@PathVariable("id") Integer id){
      ModelAndView modelAndView03 = new ModelAndView("sysuser/edit");
      //在后端数据库中查询
        SysUser id1 = service.getById(id);
        //查询到的信息放到视图中
        modelAndView03.addObject("user",id1);
        return modelAndView03;
    }
    @PostMapping("/edit")
    public R edit(@RequestBody SysUser sysUser){
        boolean update01 = service.updateById(sysUser);
        if(update01){
            return R.ok("修改成功");
        }else{
            return R.fail("修改失败");
        }
    }

    @DeleteMapping("/batchDelete")
    public R batchDelete(@RequestBody List<Integer> ids){
        List<SysUser> list = new ArrayList<>();
        //遍历集合
        for (Integer id:ids) {
            //实例化对象
            SysUser sysUser = new SysUser();
            //确认删除
            sysUser.setIsDel(true);
            sysUser.setId(id);
            list.add(sysUser);
        }
        //更新id
        boolean b = service.updateBatchById(list);
        if(b){
            return R.ok("删除成功！");
        }else {
            return R.fail("删除失败！");
        }
    }
    /**
     * 测试批量删除
     * 1.id中必须有值
     * 2.Sysuser中必须添加有参构造方法
     */
    @PostMapping("/test")
    public R test(@RequestBody List<SysUser> sysUsers){
        boolean b = service.updateBatchById(sysUsers);
        if(b){
            return R.ok("删除成功！");
        }else {
            return R.fail("删除失败！");
        }
    }
  }


